package cn.hx.admin.controller;

import cn.hx.admin.entity.LoginInfor;
import cn.hx.admin.entity.Menu;
import cn.hx.admin.entity.User;
import cn.hx.admin.entity.UserSign;
import cn.hx.admin.service.MenuService;
import cn.hx.admin.service.UserService;
import cn.hx.admin.service.UserSignService;
import cn.hx.admin.service.impl.LoginInforServiceImpl;
import cn.hx.admin.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户信息表(User)表控制层
 *
 * @author makejava
 * @since 2023-12-07 15:02:43
 */
@RestController
//@RequestMapping("user")
public class PublicController {
    // user头像上传 注意：E://images/image/
    @Value("${uploadPath}")
    private String uploadPath;
    @Autowired
    RedisUtil<Object> redisUtil;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    LoginInforServiceImpl loginInformService;

    @PostMapping(value = "login")
    public ResponseEntity<String> login(@RequestBody User user, HttpServletRequest request) {
        System.out.println("login中收到的user对象： " + user);
        // 根据账号密码 创建 UsernamePasswordAuthenticationToken 为了给认证管理器进行认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        LoginInfor loginInfor = new LoginInfor();
        /**
         * 调用AuthenticationManager的authenticate方法进行认证
         * 登录日志记录
         */
        String ip = request.getRemoteAddr();
        loginInfor.setIpaddr(ip);
        loginInfor.setLoginTime(new Date());
        loginInfor.setUserName(user.getUsername());
        String browser = request.getHeader("User-Agent");
        if (browser != null) {
            if (browser.contains("Windows")) {
                loginInfor.setOperatingSystem("Windows");
            } else if (browser.contains("Mac")) {
                loginInfor.setOperatingSystem("Mac");
            } else if (browser.contains("Linux")) {
                loginInfor.setOperatingSystem("Linux");
            }else {
                loginInfor.setOperatingSystem("未知");
            }
            if (browser.contains("Chrome")) {
                loginInfor.setLoginBrowser("Chrome");;
            } else if (browser.contains("Firefox")) {
                loginInfor.setLoginBrowser("Firefox");;
            } else {
                loginInfor.setLoginBrowser("未知");;
            }
        }
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(authenticationToken);
            loginInfor.setType("成功");
            loginInfor.setOperation("登录成功");
        } catch (Exception e) {
            loginInfor.setType("失败");
            loginInfor.setOperation("用户名密码错误");
            e.printStackTrace();
        }finally {
            loginInformService.insertLog(loginInfor);
        }
        if (authentication==null){
            throw new RuntimeException("用户名或密码错误");
        }

        Object principal = authentication.getPrincipal();
        //principal用户数据存redis 原因 Authentication 无法反序列化
        String uuid = UUID.randomUUID().toString();
        //将用户的数据存储
        redisUtil.set(uuid, principal);
        return ResponseEntity.ok(uuid);
    }

    @PostMapping(value = "userInfo")
    public ResponseEntity<User> userInfo() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return ResponseEntity.ok(principal);
    }

    @Autowired
    private MenuService menuService;

    @PostMapping(value = "menuInfo")
    public ResponseEntity<List<Menu>> menuInfo() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer roleId = principal.getRoleId();
        List<Menu> menus;
        if (roleId == 1) {
            menus = menuService.queryByPage(null);
        } else {
            menus = menuService.queryByRoleId(roleId);
        }
        return ResponseEntity.ok(menus);
    }

    @PostMapping(value = "logoutUser")
    public ResponseEntity<Void> logout(@RequestHeader("Authorization") String token) {
        redisUtil.deleteKey(token);
        return ResponseEntity.ok().build();
    }

    /**
     * @param file user用户头像文件上传
     * @return 上传的位置为 E://images/image/ 大家自己注意哈
     * @throws IOException
     */
    @PostMapping("upload")
    public ResponseEntity upload(MultipartFile file) throws IOException {
        if (file != null && !file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String type = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            file.transferTo(new File(uploadPath + "image/" + uuid + type));
            return ResponseEntity.ok("image/" + uuid + type);
        }
        return ResponseEntity.ok(HttpStatus.BAD_REQUEST);
    }
    @Resource
    private UserSignService userSignService;

    /**
     * 设备自动打卡
     * @param userSign
     * @return
     */
    @PostMapping("sign")
    public ResponseEntity<UserSign> add(UserSign userSign) {
        return ResponseEntity.ok(this.userSignService.insert(userSign));
    }
    @Resource
    private UserService userService;
    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @return 查询结果
     */
    @GetMapping("userList")
    public ResponseEntity<List<User>> queryByPage(User user) {
        return ResponseEntity.ok(this.userService.queryByPage(user));
    }

}

